/**************************************************************************************************

	NSurvey - The web survey and form engine
	Copyright (c) 2004, Thomas Zumbrunn. (http://www.nsurvey.org)

	Dotnetnuke PA module 
	Copyright (c) 2004, Oliver Hine (oliver.hine@gmail.com)

	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.


************************************************************************************************/

using DotNetNuke;
using System;
using System.Collections.Specialized;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Votations.NSurvey.DataAccess;
using Votations.NSurvey.Data;
using Votations.NSurvey.BusinessRules;
using Votations.NSurvey.WebAdmin.UserControls;
using Votations.NSurvey.Security;
using Microsoft.VisualBasic;

namespace Votations.NSurvey.WebAdmin
{
	public class ExportData : PageBase
	{
		protected System.Web.UI.WebControls.Label MessageLabel;
		protected System.Web.UI.WebControls.Label CreationDateLabel;
		protected HeaderControl Header;
		protected System.Web.UI.WebControls.Button ExportDataButton;
		protected System.Web.UI.WebControls.TextBox StartDateTextBox;
		protected System.Web.UI.WebControls.TextBox EndDateTextBox;
		protected System.Web.UI.WebControls.TextBox TextDelimiterTextBox;
		protected System.Web.UI.WebControls.TextBox FieldDelimiterTextBox;
		protected System.Web.UI.WebControls.Literal FieldDelimiterLabel;
		protected System.Web.UI.WebControls.Literal TextDelimiterLabel;
		protected System.Web.UI.WebControls.Literal ExportFromDateLabel;
		protected System.Web.UI.WebControls.Literal ExportToDateLabel;
		protected System.Web.UI.WebControls.Button VoterExportXMLButton;
		protected System.Web.UI.WebControls.Literal SurveyExportTitle;
		protected SurveyListControl SurveyList;

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
			
			CreateLinks();
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.ExportDataButton.Click += new System.EventHandler(this.ExportCSVButton_Click);
			this.VoterExportXMLButton.Click += new System.EventHandler(this.VoterExportXMLButton_Click);
			this.Load += new System.EventHandler(this.Page_Load);
		}
		#endregion

		private void Page_Load(object sender, System.EventArgs e)
		{
			try
			{
				SetupSecurity();
				LocalizePage();

				if (!Page.IsPostBack)
				{
					SurveyList.SurveyId = SurveyId;
					SurveyList.BindDropDown();
					Header.SurveyId = SurveyId;
					StartDateTextBox.Text = new DateTime(2003,12,31).ToShortDateString();
					EndDateTextBox.Text = DateTime.Now.ToShortDateString();
				}
			}
			catch( Exception exc)
			{
				DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this,exc);
			}
		}

		private void SetupSecurity()
		{
			CheckRight(NSurveyRights.AccessExport, true);
		}

		private void LocalizePage()
		{
			FieldDelimiterLabel.Text = GetPageResource("FieldDelimiterLabel");
			TextDelimiterLabel.Text = GetPageResource("TextDelimiterLabel");
			ExportFromDateLabel.Text = GetPageResource("ExportFromDateLabel");
			ExportToDateLabel.Text = GetPageResource("ExportToDateLabel");
			FieldDelimiterLabel.Text = GetPageResource("FieldDelimiterLabel");
			FieldDelimiterLabel.Text = GetPageResource("FieldDelimiterLabel");
			SurveyExportTitle.Text = GetPageResource("SurveyExportTitle");
			ExportDataButton.Text = GetPageResource("ExportDataButton");
			VoterExportXMLButton.Text = GetPageResource("VoterExportXMLButton");
		}

		/// <summary>
		/// Create and sends the CSV file to the client
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void ExportCSVButton_Click(object sender, System.EventArgs e)
		{

			Response.Charset = "utf-8";
			//Response.ContentEncoding = System.Text.Encoding.Unicode; 
			Response.ContentType = "application/octet-stream";
			Response.AddHeader("Content-Disposition", "attachment; filename=\"dataexport.csv\"");
			
			DateTime startDate = (StartDateTextBox.Text == null && !Information.IsDate(StartDateTextBox.Text)) ? 
				new DateTime(2004,1,1) : DateTime.Parse(StartDateTextBox.Text);
			DateTime endDate = (EndDateTextBox.Text == null && !Information.IsDate(EndDateTextBox.Text)) ? 
				new DateTime(2004,1,1) : DateTime.Parse(EndDateTextBox.Text);

			Response.Write(ExportCSV());
			Response.End();
		}

		private void VoterExportXMLButton_Click(object sender, System.EventArgs e)
		{
			DateTime startDate = (StartDateTextBox.Text == null && !Information.IsDate(StartDateTextBox.Text)) ? 
				new DateTime(2004,1,1) : DateTime.Parse(StartDateTextBox.Text);
			DateTime endDate = (EndDateTextBox.Text == null && !Information.IsDate(EndDateTextBox.Text)) ? 
				new DateTime(2004,1,1) : DateTime.Parse(EndDateTextBox.Text);

			Response.Charset = "utf-8";
			Response.ContentType = "application/octet-stream";
			
			Response.ContentType = "text/xml";
			Response.AddHeader("Content-Disposition", "attachment; filename=\"nsurvey_results"+SurveyId+".xml\"");
		
			NSurveyVoter voterAnswers = new Voters().GetForExport(SurveyId, startDate, endDate);
		
			WebSecurityAddInCollection securityAddIns = WebSecurityAddInFactory.CreateWebSecurityAddInCollection(new SecurityAddIns().GetWebSecurityAddIns(SurveyId), ViewState);
			NameValueCollection addInVoterData;

			if (voterAnswers.Voter.Rows.Count > 0)
			{
				// Get security addins data if any available and get key name
				// to add it as new column to the voter table
				for (int i=0;i<securityAddIns.Count;i++)
				{
					addInVoterData = securityAddIns[i].GetAddInVoterData(voterAnswers.Voter[0].VoterID);
					if (addInVoterData != null)
					{
						for (int j=0;j<addInVoterData.Count;j++)
						{
							voterAnswers.Voter.Columns.Add(new DataColumn(addInVoterData.GetKey(j), typeof(string), null, System.Data.MappingType.Element));
						}
					}
				}

				for (int voterIndex=0;voterIndex<voterAnswers.Voter.Rows.Count;voterIndex++)
				{
					// Get security addins data if any available
					for (int i=0;i<securityAddIns.Count;i++)
					{
						addInVoterData = 
							securityAddIns[i].GetAddInVoterData(((NSurveyVoter.VoterRow)voterAnswers.Voter.Rows[voterIndex]).VoterID);
						if (addInVoterData != null)
						{
							for (int j=0;j<addInVoterData.Count;j++)
							{
								voterAnswers.Voter.Rows[voterIndex][addInVoterData.GetKey(j)] = addInVoterData[j];
							}
						}
					}
				}
			}

			voterAnswers.WriteXml(Response.OutputStream, System.Data.XmlWriteMode.IgnoreSchema);

			Response.End();
		}

		private string ExportCSV()
		{
			DateTime startDate = (StartDateTextBox.Text == null && !Information.IsDate(StartDateTextBox.Text)) ? 
				new DateTime(2004,1,1) : DateTime.Parse(StartDateTextBox.Text);
			DateTime endDate = (EndDateTextBox.Text == null && !Information.IsDate(EndDateTextBox.Text)) ? 
				new DateTime(2004,1,1) : DateTime.Parse(EndDateTextBox.Text);

			System.Text.StringBuilder csvData = new System.Text.StringBuilder();
			bool scored = new Surveys().IsSurveyScored(SurveyId);

			// Get an instance of the voter DAL using the DALFactory
			CSVExportData  csvExportData = new Voters().GetCSVExport(SurveyId, startDate, endDate);

			string textDelimiter = TextDelimiterTextBox.Text,
				fieldDelimiter = FieldDelimiterTextBox.Text;

			csvData.Append(textDelimiter+"VoterID"+textDelimiter);
			csvData.Append(fieldDelimiter+textDelimiter+"Start date"+textDelimiter);
			csvData.Append(fieldDelimiter+textDelimiter+"End date"+textDelimiter);
			csvData.Append(fieldDelimiter+textDelimiter+"IP"+textDelimiter);
			if (scored)
			{
				csvData.Append(fieldDelimiter+textDelimiter+"Score"+textDelimiter);
			}
			csvData.Append(fieldDelimiter+textDelimiter+"Email"+textDelimiter);
			csvData.Append(fieldDelimiter+textDelimiter+"UserName"+textDelimiter);

			// Build CSV header
			foreach (CSVExportData.ExportAnswersRow headerColumn in csvExportData.ExportAnswers.Rows)
			{
				csvData.Append(fieldDelimiter+textDelimiter+headerColumn.ColumnHeader.Replace(textDelimiter, textDelimiter+textDelimiter)+textDelimiter);
			}

			WebSecurityAddInCollection securityAddIns = WebSecurityAddInFactory.CreateWebSecurityAddInCollection(new SecurityAddIns().GetWebSecurityAddIns(SurveyId), ViewState);
			NameValueCollection addInVoterData;

			if (csvExportData.Voters.Rows.Count > 0)
			{
				// Get security addins data if any available and get key name
				// to add to the export header
				for (int i=0;i<securityAddIns.Count;i++)
				{
					addInVoterData = securityAddIns[i].GetAddInVoterData(csvExportData.Voters[0].VoterID);
					if (addInVoterData != null)
					{
						for (int j=0;j<addInVoterData.Count;j++)
						{
							csvData.Append(string.Format("{0}{1}{2}{1}", 
								fieldDelimiter, textDelimiter, addInVoterData.GetKey(j).Replace(textDelimiter, textDelimiter+textDelimiter)));
						}
					}
				}
			}

			foreach (CSVExportData.VotersRow voter in csvExportData.Voters.Rows)
			{
				csvData.Append(System.Environment.NewLine);
				csvData.Append(textDelimiter+voter.VoterID+textDelimiter);
				csvData.Append(fieldDelimiter+textDelimiter+voter.StartDate+textDelimiter);
				csvData.Append(fieldDelimiter+textDelimiter+voter.VoteDate+textDelimiter);
				csvData.Append(fieldDelimiter+textDelimiter+voter.IPSource+textDelimiter);
				if (scored)
				{
					csvData.Append(fieldDelimiter+textDelimiter+voter.Score+textDelimiter);
				}
				csvData.Append(fieldDelimiter+textDelimiter+voter.Email+textDelimiter);
				csvData.Append(fieldDelimiter+textDelimiter+voter.UserName+textDelimiter);

				// reparse all answers to see which answer was answered or not by the voter
				foreach (CSVExportData.ExportAnswersRow headerColumn in csvExportData.ExportAnswers.Rows)
				{
					// Check if the voter has answered
					CSVExportData.VoterAnswersRow[] answer = (CSVExportData.VoterAnswersRow[])csvExportData.VoterAnswers.Select(string.Format("VoterID={0} AND AnswerID = {1}", 
						voter.VoterID, headerColumn.AnswerId));
					if (answer.Length > 0)
					{
						if (answer[0].IsAnswerTextNull())
						{								  
							csvData.Append(fieldDelimiter+textDelimiter+1+textDelimiter);
						}
						else
						{
							csvData.Append(fieldDelimiter+textDelimiter+answer[0].AnswerText+textDelimiter);
						}
					}
					else
					{
						csvData.Append(fieldDelimiter+textDelimiter+textDelimiter);
					}
				}

				// Get security addins data if any available
				for (int i=0;i<securityAddIns.Count;i++)
				{
					addInVoterData = securityAddIns[i].GetAddInVoterData(voter.VoterID);
					if (addInVoterData != null)
					{
						for (int j=0;j<addInVoterData.Count;j++)
						{
							csvData.Append(string.Format("{0}{1}{2}{1}", 
								fieldDelimiter, textDelimiter, addInVoterData[j].Replace(textDelimiter, textDelimiter+textDelimiter)));
						}
					}
				}
			}

			return csvData.ToString();
		}
	}
}
